package com.lanhao.aot.sharding;

import java.util.Iterator;

public class CommonPreciseShardingAlgorithm {
	private static boolean isEmpty(Object value) {
		if (value instanceof Long) {
			long v = (long) value;
			return v == 0;
		}
		return value == null;
	}

	public static boolean is2Power(int length) {
		return (length & (length - 1)) == 0;
	}

	public static Integer getShardingIndex(int length, Object value) {
		Integer index = null;
		if (isEmpty(value)) {
			return null;
		} else {
			int h;
			int hash = (h = value.hashCode()) ^ (h >>> 16);

			if (is2Power(length)) {
				index = (length - 1) & hash;
			} else {
				index = Math.floorMod(hash, length);
			}
		}
		return index;
	}

	
	public static void main(String[] args) {
		long startTimeMillis = System.currentTimeMillis();
		Integer shardingIndex = getShardingIndex(32, "3TPC034332PAGEG");
		System.out.println(shardingIndex);
		long endTimeMillis = System.currentTimeMillis();
		
		System.out.println((endTimeMillis - startTimeMillis) + "ms");
	}
}
